package com.alpsoft.spotcheck.util;

import java.io.File;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Point;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alpsoft.spotcheck.model.Attachment;
import com.alpsot.lkspotcheck.R;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

/**
 * 数据上传
 * @author zz.han 2015年5月15日 上午11:29:34
 */
@SuppressLint("ResourceAsColor")
public class UploadDataManager {

	private TextView picresult;
	// TextView dataresult;
	private TextView currentnowtext;
	private Context mContext;
	/* 更新进度条 */
	private ProgressBar mProgress;
	private Dialog mUpDataDialog;
	private Button okbtn;

	private int datalength = 1;
	private int listindex = 0;
	// 大坨数据包
	private Map<String, Object> dataMap = null;
	// 点检附件表
	private List<Attachment> attlist = null;
	// 数据工具
	private DataHelper dh;
	// 最终结果
	private boolean b;
	private String type = null;

	public UploadDataManager(Context context) {
		this.mContext = context;
		this.dh = new DataHelper(context);
	}

	/**
	 * 检是否有要提交的数据
	 * 
	 * @param type
	 */
	public void checkDataUpInfo(String type) {
		if (!Utils.isConnectedNetwork(mContext)) {
			// 提示开启网络
			AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
			builder.setMessage("无法连接网络，请检查网络是否连接!");
			AlertDialog dialog = builder.create();
			// dialog.setCancelable(false);
			// dialog.setCanceledOnTouchOutside(false);
			dialog.show();
		} else {
			if (type.equals("update_dj")) {
				GlobalVar.ts.speak("准备提交数据");
				if (isUpdate()) {
					showupdataDialog();
				} else {
					Toast.makeText(mContext, R.string.data_up_no,
							Toast.LENGTH_LONG).show();
				}
			}
		}
	}

	/**
	 * 检查是否有需要提交的数据
	 * 
	 * @return
	 */
	private boolean isUpdate() {
		if (dh.hasLocalData()) {
			dataMap = dh.getDataMap();
			attlist = dh.getAttachList();
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 显示数据上传对话框
	 */
	@SuppressLint("NewApi")
	private void showupdataDialog() {
		// 构造数据上传对话框
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle("点检数据上传");
		// builder.setMessage(R.string.data_uping);
		// 给上传对话框增加进度条
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.uploaddata, null);
		mProgress = (ProgressBar) v.findViewById(R.id.total);
		picresult = (TextView) v.findViewById(R.id.picresult);
		picresult.setTextColor(R.color.bg_blue_deep);
		okbtn = (Button) v.findViewById(R.id.okbtn);
		okbtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Message msg = new Message();
				if (b) {
					msg.what = GlobalVar.msg_UploadSuccess;
				} else {
					msg.what = GlobalVar.msg_UploadFailure;
				}
				GlobalVar.ts.speak("数据上传完成");
				mUpDataDialog.dismiss();
			}
		});
		currentnowtext = (TextView) v.findViewById(R.id.currentnowtext);
		currentnowtext.setText("");
		builder.setView(v);
		mUpDataDialog = builder.create();
		mUpDataDialog.setCancelable(false);
		mUpDataDialog.setCanceledOnTouchOutside(false);
		mUpDataDialog.show();

		WindowManager wm = (WindowManager) mContext
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		WindowManager.LayoutParams lp = mUpDataDialog.getWindow()
				.getAttributes();
		Point size = new Point();
		display.getSize(size);
		lp.width = (int) (size.x * 0.7);
		// lp.height = size.y;
		mUpDataDialog.getWindow().setAttributes(lp);
		upData();
	}

	/**
	 * 提交数据
	 */
	private void upData() {
		// 启动新线程提交数据
		new upDataThread().start();
	}

	/**
	 * 上传数据线程
	 * 
	 * @author hanzz
	 * @date 2015-4-30
	 */
	private class upDataThread extends Thread {

		String upfilepath = GlobalVar.upfilepath;
		String updatapath = GlobalVar.updatapath;
		private Handler mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {

				case 0:
					b = true;
					picresult.setText("未提交。没有要上传的数据");
					okbtn.setEnabled(true);
					okbtn.performClick();

					break;
				case 1:
					mProgress.setProgress(0);
					currentnowtext.setText("正在上传第：" + 1 + "项。  共：" + datalength
							+ "项");
					break;
				case -1:
					b = false;
					picresult.setText("失败。网络出现异常");
					picresult.setTextColor(android.graphics.Color.RED);
					okbtn.setEnabled(true);
					break;

				case -2:
					b = false;
					picresult.setText("照片读取异常，检查内存卡");
					okbtn.setEnabled(true);
					break;
				case -9:
					b = false;
					picresult.setText("服务器处理失败");
					picresult.setTextColor(android.graphics.Color.RED);
					okbtn.setEnabled(true);
					break;
				case 11:
					if (listindex < attlist.size()) {
						mProgress
								.setProgress((int) (((float) listindex / datalength) * 100));
						currentnowtext.setText("正在上传第：" + (1 + listindex)
								+ "项。  共：" + datalength + "项");
						sentFile();
					} else {
						mProgress
								.setProgress((int) (((float) listindex / datalength) * 100));
						currentnowtext.setText("正在上传第：" + (1 + listindex)
								+ "项。  共：" + datalength + "项");
						sentData();
					}
					break;
				case 9:
					b = true;
					mProgress.setProgress(100);
					picresult.setText("全部数据上传完成！");
					currentnowtext.setText("");
					SystemClock.sleep(2000);
					okbtn.setEnabled(true);
					okbtn.performClick();
					break;
				default:
					break;
				}
			};
		};

		public void run() {
			if (dataMap == null && attlist == null) {
				mHandler.sendEmptyMessage(0);
				return;
			}
			if (attlist != null && attlist.size() > 0) {
				datalength += attlist.size();
				mHandler.sendEmptyMessage(1);
				sentFile();
			} else {
				mHandler.sendEmptyMessage(1);
				sentData();
			}
		}

		private void sentData() {
			String bigdata = new Gson().toJson(dataMap);
			RequestParams params = new RequestParams();
			params.addBodyParameter("json", bigdata);
			HttpUtils http = new HttpUtils(600 * 1000);
			String sessionId = SharedPreferencesUtils.getSessionId(mContext);
			// oConn.setRequestProperty("cookie", "JSESSIONID=" +
			// sessionId);
			params.setHeader("cookie", "JSESSIONID=" + sessionId);
			http.send(HttpMethod.POST, updatapath, params,
					new RequestCallBack<String>() {

						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							Log.w("response", responseInfo.result);
							try {
								JSONObject obj = new JSONObject(
										responseInfo.result);
								if ("SUCCESS".equals(obj.get("result"))) {
									mHandler.sendEmptyMessage(9);
								} else {
									mHandler.sendEmptyMessage(-9);
								}
							} catch (Exception e) {
								e.printStackTrace();
								mHandler.sendEmptyMessage(-9);
							}
						}

						@Override
						public void onFailure(HttpException error, String msg) {
							Log.w("response", error.getExceptionCode() + ":"
									+ msg);
							mHandler.sendEmptyMessage(-1);
						}
					});
		}

		void sentFile() {
			Attachment att = attlist.get(listindex);

			// 该条记录存在文件信息，才进行下一步，没文件信息，跳过。
			if (att.getFilePath() != null && !"".equals(att.getFilePath())) {
				// 判断SD卡是否存在，并且是否具有读写权限
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					String filePath = att.getFilePath();
					File file = new File(filePath);
					// 照片存在，进行下一步
					if (file.exists()) {
						HttpUtils hu = new HttpUtils(600 * 1000);
						RequestParams params = new RequestParams();
						String jsonStr = new Gson().toJson(att);
						params.addBodyParameter("json", jsonStr);
						String sessionId = SharedPreferencesUtils
								.getSessionId(mContext);
						params.setHeader("cookie", "JSESSIONID=" + sessionId);
						params.addBodyParameter("file", file);
						hu.send(HttpMethod.POST, upfilepath, params,
								new RequestCallBack<String>() {
									@Override
									public void onStart() {
										// currentbar.setProgress(0);
									}

									@Override
									public void onLoading(long all, long now,
											boolean isUploading) {
									}

									@Override
									public void onSuccess(
											ResponseInfo<String> responseInfo) {
										// current.setProgress(100);
										// total.setProgress((int) (((float)
										// j /
										// size) * 100));
										Log.w("list.response",
												responseInfo.result);
										try {
											JSONObject obj = new JSONObject(
													responseInfo.result);
											if ("SUCCESS".equals(obj
													.get("result"))) {
												listindex++;
												mHandler.sendEmptyMessage(11);
											} else {
												mHandler.sendEmptyMessage(-9);
											}
										} catch (Exception e) {
											e.printStackTrace();
											mHandler.sendEmptyMessage(-9);
										}

									}

									@Override
									public void onFailure(HttpException error,
											String msg) {
										mHandler.sendEmptyMessage(-1);

									}
								});
						// 照片不存，跳过。
					} else {
						listindex++;
						mHandler.sendEmptyMessage(11);
					}
					// 内存卡读取异常，失败
				} else {
					mHandler.sendEmptyMessage(-2);
				}
				// 该条记录没有文件，跳过
			} else {
				listindex++;
				mHandler.sendEmptyMessage(11);
			}
		}

	}
}
